﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Web.SessionState;


/// <summary>
/// Summary description for Promotion
/// </summary>
public class Promotion
{
    BCDataCenter.DataAccessLayer.DAL dt;
    private DataSet Rs, Rss;
    private bool PromotionByCustomer = false;
	public Promotion()
	{
		//
		// TODO: Add constructor logic here
		//
	}    
   
    private void ParsePay(string username)
    {
        //string username = "dss1";
        string tableName = username + "OUTPUT";
        string error = "";
        dt = new BCDataCenter.DataAccessLayer.DAL();
        double tmp1, tmp2 = 0;
        bool isExist = false;
        //Kiem tra xoa va tao table user_OUTPUT
        isExist = dt.IsExistFromSQL("Get_tableName", CommandType.StoredProcedure, ref error, new SqlParameter("@usernames", username), new SqlParameter("@add", "OUTPUT"));
        if (isExist)
        {
            bool kq = dt.MyExecuteNonQuerys("Drop table " + tableName, CommandType.Text, ref error);
            if (kq)
            {
                //kq=dt.MyExecuteNonQuerys("CREATE TABLE " + tableName + " ([Itemkey] [varchar] (20) NULL ,[Qty] [float] NULL ,[Amt] [float] NULL ,[Disc] [float] NULL ,[ProgramID] [varchar] (20) NULL ,[PayProgramID] [varchar] (20) NULL ,   [ProgramType] [varchar] (10) NULL, Price Float Null, VAT varchar (10) null, LineDisc float null ) ON [PRIMARY]  ", CommandType.Text,ref error);
                if (kq)
                {
                    error = "OK";
                }
            }
        }
        dt.MyExecuteNonQuerys("CREATE TABLE " + tableName + " ([Itemkey] [varchar] (20) NULL ,[Qty] [float] NULL ,[Amt] [float] NULL ,[Disc] [float] NULL ,[ProgramID] [varchar] (20) NULL ,[PayProgramID] [varchar] (20) NULL ,   [ProgramType] [varchar] (10) NULL, Price Float Null, VAT varchar (10) null, LineDisc float null ) ON [PRIMARY]  ", CommandType.Text, ref error);
        Rs = new DataSet();
        //lay ma chuong trinh km va dataset Rs
        Rs = dt.MyExecuteQuery(ref error, "Set_RS", CommandType.StoredProcedure, new SqlParameter("@usernames", username));
        int row = Rs.Tables[0].Rows.Count;
        for (int i = 0; i < row; i++)
        {
            string ProTyp = Rs.Tables[0].Rows[i]["ProType"].ToString();
            string ProID = Rs.Tables[0].Rows[i]["ProgramID"].ToString();
            float ProCounts = float.Parse(Rs.Tables[0].Rows[i]["ProCount"].ToString());

            switch (ProTyp)
            {
                case "HDTT": //Mua một bộ hàng(tính đơn vị hàng) được thưởng một số tiền :select Pvalue from ARPrPayDef where ProgramID = @ProID                   
                    //số tiền được thưởng
                    string tmp = dt.MyExecuteQuerys(ref error, "Get_PValue", CommandType.StoredProcedure, new SqlParameter("@ProID", ProID));
                    tmp2 = double.Parse(tmp);
                    dt.MyExecuteNonQuery("Insert_OUTPUTHDTT", CommandType.StoredProcedure, ref error, new SqlParameter("@usernames", username), new SqlParameter("@Amt", tmp2 * ProCounts), new SqlParameter("@ProgramID", ProID), new SqlParameter("@Programtype", ProTyp));
                    //Luong hang tham gia chuong trinh KM nay
                    dt.MyExecuteNonQuery("insert_fromTMP2", CommandType.StoredProcedure, ref error, new SqlParameter("@usernames", username), new SqlParameter("@procount", ProCounts), new SqlParameter("@ProgramID", ProID));
                    break;
                case "HDTH"://mua mot bo hang(tinh don vi hang)được thưởng một bộ hàng(khác)
                    dt.MyExecuteNonQuery("Insert_OUTPUTHDTH", CommandType.StoredProcedure, ref error, new SqlParameter("@usernames", username), new SqlParameter("@procount", ProCounts), new SqlParameter("@ProgramID", ProID), new SqlParameter("@Programtype", ProTyp));
                    dt.MyExecuteNonQuery("insert_frTMP2", CommandType.StoredProcedure, ref error, new SqlParameter("@usernames", username), new SqlParameter("@procount", ProCounts), new SqlParameter("@ProgramID", ProID));
                    dt.MyExecuteNonQuery("insert_fromTMP2", CommandType.StoredProcedure, ref error, new SqlParameter("@usernames", username), new SqlParameter("@procount", ProCounts), new SqlParameter("@ProgramID", ProID));
                    //dt.MyExecuteNonQuery("update_OUTPUT", CommandType.StoredProcedure, ref error, new SqlParameter("@usernames", username), new SqlParameter("@ProgramID", ProID));
                    break;
                case "HDCK"://khong su dung truong hop nay neu co thi dung loai HDTT de thay the
                    break;
                case "HSTT"://Mua mot vai mat hang trong mot list dat muc-->thuong theo so tien(VD:trong 4 mat hang,mua tong la 3 thi thuong 2000 VND,mua tong la 5 thuong 40000 VND)
                    tmp1 = double.Parse(Rs.Tables[0].Rows[i]["ProCount"].ToString());
                    Rss = new DataSet();
                    Rss = dt.MyExecuteQuery(ref error, "Set_RSS", CommandType.StoredProcedure, new SqlParameter("@usernames", username), new SqlParameter("@ProgramID", ProID));
                    int rows = Rss.Tables[0].Rows.Count;
                    for (int y = 0; y < rows; y++)
                    {
                        if (tmp1 > double.Parse(Rss.Tables[0].Rows[y]["Quantity"].ToString()))
                            tmp2 = double.Parse(Rss.Tables[0].Rows[y]["Quantity"].ToString());
                        else
                            tmp2 = tmp1;
                        //maindatabase.Execute " insert into dbo." & login_name & "OUTPUT Values('" & Rss("SKUCode") & "', " & Tmp2 & ", 0, 0, '" & Rs("ProgramID") & "','','" & Rs("ProType") & "',0,'VAT',0 )"
                        string itemkey = Rss.Tables[0].Rows[y]["SKUCode"].ToString();
                        dt.MyExecuteNonQuery("insert_OUTPUTHSTT", CommandType.StoredProcedure, ref error, new SqlParameter("@usernames", username), new SqlParameter("@tmp2", tmp2), new SqlParameter("@ProgramID", ProID), new SqlParameter("@itemkey", itemkey), new SqlParameter("@ProgramType", ProTyp));
                        tmp1 = tmp1 - tmp2;
                        if (tmp1 <= 0)
                            break;
                    }
                    dt.MyExecuteNonQuerys("insert into " + username + "OUTPUT select '', 1,PValue, 0,  '" + ProID + "','','" + ProTyp + "',0,'VAT',0 from dbo.ARPRPayDef where ProgramID = '" + ProID + "' and rangeValue =" + ProCounts, CommandType.Text, ref error);
                    //dt.MyExecuteNonQuery("insert_FromARPrPayDef", CommandType.StoredProcedure, ref error, new SqlParameter("@usernames", username), new SqlParameter("@procount", ProCounts), new SqlParameter("@ProgramID", ProID), new SqlParameter("@ProgramType", ProTyp));
                    break;
                case "HSTH"://mua mot vai mat hang trong mot list dat theo muc--> thuong bo hang tuong ung (VD:trong 4 mat hang ,mua tong la 3 thi thuong skim a,mua tong la 5 thuong skim b,a&b la list cac mat hang)
                    tmp1 = double.Parse(Rs.Tables[0].Rows[i]["ProCount"].ToString());
                    Rss = new DataSet();
                    Rss = dt.MyExecuteQuery(ref error, "Set_RSS", CommandType.StoredProcedure, new SqlParameter("@usernames", username), new SqlParameter("@ProgramID", ProID));
                    int rowss = Rss.Tables[0].Rows.Count;
                    for (int yi = 0; yi < rowss; yi++)
                    {
                        if (tmp1 > double.Parse(Rss.Tables[0].Rows[yi]["Quantity"].ToString()))
                            tmp2 = double.Parse(Rss.Tables[0].Rows[yi]["Quantity"].ToString());
                        else
                            tmp2 = tmp1;
                        //maindatabase.Execute " insert into dbo." & login_name & "OUTPUT Values('" & Rss("SKUCode") & "', " & Tmp2 & ", 0, 0, '" & Rs("ProgramID") & "','','" & Rs("ProType") & "',0,'VAT',0 )"
                        string itemkey = Rss.Tables[0].Rows[yi]["SKUCode"].ToString();
                        dt.MyExecuteNonQuery("insert_OUTPUTHSTH", CommandType.StoredProcedure, ref error, new SqlParameter("@usernames", username), new SqlParameter("@tmp2", tmp2), new SqlParameter("@ProgramID", ProID), new SqlParameter("@itemkey", itemkey), new SqlParameter("@Programtype", ProTyp));
                        tmp1 = tmp1 - tmp2;
                        if (tmp1 <= 0)
                            break;
                    }
                    dt.MyExecuteNonQuery("Insert_OUTPUTHSTH1", CommandType.StoredProcedure, ref error, new SqlParameter("@usernames", username), new SqlParameter("@procount", ProCounts), new SqlParameter("@ProgramID", ProID), new SqlParameter("@Programtype", ProTyp));
                    //dt.MyExecuteNonQuery("update_OUTPUTHSTH1", CommandType.StoredProcedure, ref error, new SqlParameter("@usernames", username), new SqlParameter("@procount", ProCounts), new SqlParameter("@ProgramID", ProID), new SqlParameter("@Programtype", ProTyp));

                    break;
                case "HSCK"://khong su dung truong hop nay ,neu co thi dung loai TSCK de thay the
                    break;
                case "TDTT"://su dung HDTT de thay the vi ban chat tuong tu nhau
                    break;
                case "TDTH"://su dung HDTH de thay the vi ban chat tuong tu nhau
                    break;
                case "TDCK"://su dung HDTT de thay the vi ban chat tuong tu nhau
                    break;
                case "TSTT"://su dung HSTT de tranh truong hop muc thuong chia cho so hang bi le
                    tmp1 = double.Parse(Rs.Tables[0].Rows[i]["ProCount"].ToString());
                    Rss = new DataSet();
                    Rss = dt.MyExecuteQuery(ref error, "Set_RssTSTT", CommandType.StoredProcedure, new SqlParameter("@usernames", username), new SqlParameter("@ProgramID", ProID));
                    int rrow = Rss.Tables[0].Rows.Count;
                    for (int z = 0; z < rrow; z++)
                    {
                        if (tmp1 > double.Parse(Rss.Tables[0].Rows[z]["AMount"].ToString()))
                            tmp2 = double.Parse(Rss.Tables[0].Rows[z]["AMount"].ToString());
                        else
                            tmp2 = tmp1;
                        string itemkey = Rss.Tables[0].Rows[z]["SKUCode"].ToString();
                        string sql = " insert into dbo." + username + "OUTPUT Values('" + itemkey + "', 0," + tmp2 + ",  0, '', '" + ProID + "','" + ProTyp + "',0,'VAT',0 )";
                        dt.MyExecuteNonQuerys(sql, CommandType.Text, ref error);
                        //dt.MyExecuteNonQuery("insert_OUTPUTTSTT", CommandType.StoredProcedure, ref error, new SqlParameter("@usernames", username), new SqlParameter("@tmp2", tmp2), new SqlParameter("@ProgramID", ProID), new SqlParameter("@itemkey", itemkey),new SqlParameter("@ProgramType",ProTyp));
                        tmp1 = tmp1 - tmp2;
                        if (tmp1 <= 0)
                            break;
                    }
                    string sql2 = "insert into dbo." +username+ "OUTPUT Select '', 1,PValue , 0,'" +ProID+"','','" +ProTyp+ "', 0,'VAT', 0 from   dbo.ARPrPayDef P  where programID = '" +ProID+ "' and RangeValue ="+ProCounts;
                    //dt.MyExecuteNonQuerys("insert into " + username + "OUTPUT select '', 1,PValue, 0,  '" + ProID + "','','" + ProTyp + "',0,'VAT',0 from dbo.ARPRPayDef where ProgramID = '" + ProID + "' and rangeValue =" + ProCounts, CommandType.Text, ref error);
                    dt.MyExecuteNonQuerys(sql2, CommandType.Text, ref error);
                    sql2 = "update dbo." +username+ "OUTPUT set qty = amt* quantity / amount, Price = iPrice, VAT = IVAT, LineDisc = ILineDisc from dbo." +username+ "INPUT where " +username+"INPUT.Itemkey = " +username+ "OUTPUT.Itemkey and PayProgramID = '" +ProID+ "' ";    
                //dt.MyExecuteNonQuery("update_OUTPUT", CommandType.StoredProcedure, ref error, new SqlParameter("@usernames", username), new SqlParameter("@ProgramID", ProID));
                    dt.MyExecuteNonQuerys(sql2, CommandType.Text, ref error);   
                break;
                case "TSTH"://su dung HSTH de tranh truong hop muc thuong chia cho so hang le
                    tmp1 = double.Parse(Rs.Tables[0].Rows[i]["ProCount"].ToString());
                    Rss = new DataSet();
                    Rss = dt.MyExecuteQuery(ref error, "Set_RssHSTT", CommandType.StoredProcedure, new SqlParameter("@usernames", username), new SqlParameter("@ProgramID", ProID));
                    int rrows = Rss.Tables[0].Rows.Count;
                    for (int k = 0; i < rrows; k++)
                    {
                        if (tmp1 > double.Parse(Rss.Tables[0].Rows[k]["AMount"].ToString()))
                            tmp2 = double.Parse(Rss.Tables[0].Rows[k]["AMount"].ToString());
                        else
                            tmp2 = tmp1;
                        //maindatabase.Execute " insert into dbo." & login_name & "OUTPUT Values('" & Rss("SKUCode") & "', " & Tmp2 & ", 0, 0, '" & Rs("ProgramID") & "','','" & Rs("ProType") & "',0,'VAT',0 )"
                        string itemkey = Rss.Tables[0].Rows[k]["SKUCode"].ToString();                       
                        dt.MyExecuteNonQuery("insert_OUTPUTTSTT", CommandType.StoredProcedure, ref error, new SqlParameter("@usernames", username), new SqlParameter("@tmp2", tmp2), new SqlParameter("@ProgramID", ProID), new SqlParameter("@itemkey", itemkey));
                        tmp1 = tmp1 = tmp2;
                        if (tmp1 <= 0)
                            break;
                    }
                    dt.MyExecuteNonQuery("Insert_OUTPUTHSTH", CommandType.StoredProcedure, ref error, new SqlParameter("@usernames", username), new SqlParameter("@Amt", tmp2 * ProCounts), new SqlParameter("@ProgramID", ProID), new SqlParameter("@Programtype", ProTyp));
                    dt.MyExecuteNonQuery("update_OUTPUT", CommandType.StoredProcedure, ref error, new SqlParameter("@usernames", username), new SqlParameter("@ProgramID", ProID));
                    break;
                case "TSCK"://mua tong tien dat theo muc ,chiet khau tung muc tuong ung(trong truong hop chiet khau nay thi tat ca cac mat hang tham gia vao chuong trinh KM nay deu duoc chiet khau)
                    dt.MyExecuteNonQuery("insert_OUTPUTTSCK", CommandType.StoredProcedure, ref error, new SqlParameter("@usernames", username), new SqlParameter("@ProgramID", ProID), new SqlParameter("@Programtype", ProTyp));
                    string tm = dt.MyExecuteQuerys(ref error, "Set_TMP1", CommandType.StoredProcedure, new SqlParameter("@ProgramID", ProID), new SqlParameter("@procount", ProCounts));
                    tmp1 = double.Parse(tm);
                    //dt.MyExecuteNonQuery("insert_OUTPUTTSCK1", CommandType.StoredProcedure, ref error, new SqlParameter("@usernames", username), new SqlParameter("@ProgramID", ProID), new SqlParameter("@Programtype", ProTyp), new SqlParameter("@tmp1", tmp1), new SqlParameter("@Blank", ""));
                    dt.MyExecuteNonQuerys("insert into " + username + "OUTPUT Select '', 1, sum(Amount) *0.01*" + tmp1 + ",0, '" + ProID + "','','" + ProTyp + "',0, 'VAT', 0 from " + username + "INPUT I inner join " + username + "TMP2 T on skucode = itemkey and programID = '" + ProID + "'", CommandType.Text, ref error);

                    break;
                //end loop
            }
        }
        //Xu ly cac mat hang tham gia nhieu hon mot chuong trinh km
        bool isExists = false;
        //Kiem tra xoa va tao table user_TMP6
        isExists = dt.IsExistFromSQL("Get_tableName", CommandType.StoredProcedure, ref error, new SqlParameter("@usernames", username), new SqlParameter("@add", "TMP6"));
        if (isExists)
        {
            bool kq = dt.MyExecuteNonQuerys("Drop table " + username + "TMP6", CommandType.Text, ref error);
            if (kq)
            {
                //kq = dt.MyExecuteNonQuerys("CREATE TABLE " + username + "TMP6 ([ProgramID] [varchar] (20) NULL ,[Amount] [float] NULL ,[SKUCode] [varchar] (20) NULL ) ON [PRIMARY] ", CommandType.Text, ref error);
                //if (kq)
                {
                    error = "OK";
                }
            }
        }
        dt.MyExecuteNonQuerys("CREATE TABLE " + username + "TMP6 ([ProgramID] [varchar] (20) NULL ,[Amount] [float] NULL ,[SKUCode] [varchar] (20) NULL ) ON [PRIMARY] ", CommandType.Text, ref error);
        string txt = "", txt1 = "";
        Rs = new DataSet();
        Rs = dt.MyExecuteQuery(ref error, "set_RsWCase", CommandType.StoredProcedure, new SqlParameter("@usernames", username));
        //////--------------------------------------
        if (Rs != null)
            if (float.Parse(Rs.Tables[0].Rows[0][1].ToString()) > 1)
            {
                int numrow = Rs.Tables[0].Rows.Count;
                for (int j = 0; j < numrow; j++)
                {
                    if (float.Parse(Rs.Tables[0].Rows[j][1].ToString()) <= 1)
                        break;
                    else
                    {
                        Rss = new DataSet();
                        Rss = dt.MyExecuteReader(ref error, "select distinct PayProgramID from " + username + "OUTPUT where PayProgramID<>'' and itemkey ='" + Rs.Tables[0].Rows[j][0].ToString() + "'", CommandType.Text);
                        int numrowrss = Rss.Tables[0].Rows.Count;
                        for (int y = 0; y < numrowrss; y++)
                        {
                            //dt.MyExecuteNonQuery("Insert_TMP6", CommandType.StoredProcedure, ref error, new SqlParameter("@usernames", username), new SqlParameter("@PayProgramID", Rss.Tables[0].Rows[y]["PayProgramID"].ToString()), new SqlParameter("@SKUcode", Rs.Tables[0].Rows[j]["SkuCode"].ToString()));
                            string sql = "Insert into " + username + "TMP6 Select '" + Rss.Tables[0].Rows[y]["PayProgramID"].ToString() + "', sum(Amt ) ,'" + Rs.Tables[0].Rows[j]["SkuCode"].ToString() + "' from " + username + "OUTPUT where programID = '" + Rss.Tables[0].Rows[y]["PayProgramID"].ToString() + "'";
                            dt.MyExecuteNonQuerys(sql, CommandType.Text, ref error);
                        }
                    }
                }
                Rs = new DataSet();
                Rs = dt.MyExecuteReader(ref error, "select SKUCode,ProgramID,Amount from " + username + "TMP6 order by skucode,amount desc", CommandType.Text);
                int rn = 0;
                if (Rs != null)
                    rn = Rs.Tables[0].Rows.Count;
                for (int ii = 0; ii < rn; ii++)
                {
                    string txt2 = dt.MyExecuteQuerys(ref error, "set_txt1", CommandType.StoredProcedure, new SqlParameter("@ProgramID", Rs.Tables[0].Rows[ii]["ProgramID"].ToString()));
                    if (txt != Rs.Tables[0].Rows[ii]["SKUCode"].ToString())
                    {
                        txt = Rs.Tables[0].Rows[ii]["SKUCode"].ToString();
                        txt1 = txt2;
                    }
                    else
                    {
                        if (txt1 == "TSTH" && txt2 != txt1)
                            dt.MyExecuteNonQuery("insert_TMP7", CommandType.StoredProcedure, ref error, new SqlParameter("@ProgramID", Rs.Tables[0].Rows[ii]["ProgramID"].ToString()));
                        dt.MyExecuteNonQuery("delete_OUTPUT", CommandType.StoredProcedure, ref error, new SqlParameter("@usernames", username), new SqlParameter("@ProgramID", Rs.Tables[0].Rows[ii]["ProgramID"].ToString()));
                    }
                }
            }
        //dt.MyExecuteNonQuery("End_PayFunction", CommandType.StoredProcedure, ref error, new SqlParameter("@usernames", username));
         string sql1="Insert into dbo." +username+"PROUT select * from dbo." +username+ "OUTPUT ";
        dt.MyExecuteNonQuerys(sql1,CommandType.Text,ref error);
        sql1= "Update dbo."+username+ "INPUT set amount = amount - amt, quantity = quantity - qty from dbo." +username+"OUTPUT where " +username+ "INPUT.Itemkey = " +username+"OUTPUT.Itemkey and programID = '' ";
        dt.MyExecuteNonQuerys(sql1,CommandType.Text,ref error);
        sql1 = "Delete dbo." + username + "INPUT where amount =0 or quantity = 0 ";
        dt.MyExecuteNonQuerys(sql1, CommandType.Text, ref error);
    }

    public bool CalPromotion(string PDate, string Custkey, string username)
    {
        dt = new BCDataCenter.DataAccessLayer.DAL();
        string error = "";
        bool HavePr;
        //string username = "dss1";
        bool isExist = false;
        //Kiem tra xoa va tao table user_OUTPUT
        isExist = dt.IsExistFromSQL("Get_tableName", CommandType.StoredProcedure, ref error, new SqlParameter("@usernames", username), new SqlParameter("@add", "PrOUT"));
        if (isExist)
        {
            bool kq = dt.MyExecuteNonQuerys("Drop table " + username + "PrOUT", CommandType.Text, ref error);
            if (kq)
            {
                //kq = dt.MyExecuteNonQuerys("CREATE TABLE " + username + "OUTPUT ([Itemkey] [varchar] (20) NULL ,[Qty] [float] NULL ,[Amt] [float] NULL ,[Disc] [float] NULL ,[ProgramID] [varchar] (20) NULL ,[PayProgramID] [varchar] (20) NULL ,   [ProgramType] [varchar] (10) NULL, Price Float Null, VAT varchar (10) null, LineDisc float null ) ON [PRIMARY]  ", CommandType.Text, ref error);
                if (kq)
                {
                    error = "OK";
                }
            }
        }
        dt.MyExecuteNonQuerys("CREATE TABLE " + username + "PROUT ([Itemkey] [varchar] (20) NULL ,[Qty] [float] NULL ,[Amt] [float] NULL ,[Disc] [float] NULL ,[ProgramID] [varchar] (20) NULL ,[PayProgramID] [varchar] (20) NULL ,   [ProgramType] [varchar] (10) NULL, Price Float Null, VAT varchar (10) null, LineDisc float null ) ON [PRIMARY] ", CommandType.Text, ref error);
        //Luu cac ma chuong trinh khong the tinh km duoc(phat sinh khi co mat hang tham gia 2 chuong trinh KM,1 la TSTH va Ctr loai khac ma TSTH duoc tinh truoc
        isExist = dt.IsExistFromSQL("Get_tableName", CommandType.StoredProcedure, ref error, new SqlParameter("@usernames", username), new SqlParameter("@add", "TMP7"));
        if (isExist)
        {
            bool kq = dt.MyExecuteNonQuerys("Drop table " + username + "TMP7", CommandType.Text, ref error);
            if (kq)
            {
                //kq = dt.MyExecuteNonQuerys("CREATE TABLE " + username + "TMP7 ([ProgramID] [varchar] (20) NULL)ON [PRIMARY]  ", CommandType.Text, ref error);
                if (kq)
                {
                    error = "OK";
                }
            }
        }
        dt.MyExecuteNonQuerys("CREATE TABLE " + username + "TMP7 ([ProgramID] [varchar] (20) NULL)ON [PRIMARY]  ", CommandType.Text, ref error);
        bool CalPromotions = false;
        HavePr = false;
        int zi = 0;
        while (ParseBuy(PDate, Custkey, username))
        {
            HavePr = true;
            ParsePay(username);
            zi++;
        }

        //while (ParseBuy(PDate, Custkey))
        if (HavePr)
        {
            //co the doi thanh stored
            dt.MyExecuteNonQuerys("delete " + username + "OUTPUT", CommandType.Text, ref error);
            //dt.MyExecuteNonQuerys("insert into " + username + "OUTPUT select itemkey ,sum(Qty) as Qty,sum(Amt)as Amt,disc,ProgramID,PayProgramID,Programtype,VAT,LineDisc from " + username + "Prout where programId <> '' group by itemkey,disc,programID,PayProgramID,Prgramtype,Price,VAT,LineDisc", CommandType.Text, ref error);
            dt.MyExecuteNonQuery("insert_OUTPUT_PROUT", CommandType.StoredProcedure, ref error, new SqlParameter("@usernames", username));
            dt.MyExecuteNonQuerys("update " + username + "OUTPUT set qty =1 where right(Programtype,2) in ('TT','CK')", CommandType.Text, ref error);
            dt.MyExecuteNonQuerys("update " + username + "OUTPUT set amt = 0 where right(programtype,2) in ('TH')", CommandType.Text, ref error);
            dt.MyExecuteNonQuerys("update " + username + "OUTPUT set price = 0,VAT =''", CommandType.Text, ref error);
            string tmp = dt.MyExecuteReaders(ref  error, "select count(*) from" + username + "OUTPUT", CommandType.Text);
            if (float.Parse(tmp) > 0)
                CalPromotions = true;
            else
                CalPromotions = false;
            for (int i = 0; i < 7; i++)
            {
                dt.MyExecuteNonQuerys("if exists(select name from sysobjects where name ='" + username + "TMP" + i + "') Drop table " + username + "TMP" + i, CommandType.Text, ref error);
            }
        }
        else
        {
            CalPromotions = false;
        }
        return CalPromotions;
    }
    private bool ParseBuy(string PDate, string Custkey, string username)
    {
        bool isExist = false;
        int chanel = 1;
        string error = "";
        //string username = "dss1";
        bool tmp = false;
        Rs = new DataSet();
        string TMP3;
        for (int i = 1; i < 6; i++)
        {
            //dt.MyExecuteNonQuerys("if exists(select name from sysobjects where name =" + username + "TMP" + i + ") Drop table " + username + "TMP" + i, CommandType.Text, ref error);
            isExist = dt.IsExistFromSQL("Get_tableName", CommandType.StoredProcedure, ref error, new SqlParameter("@usernames", username), new SqlParameter("@add", "TMP" + i));
            if (isExist)
            {
                bool kq = dt.MyExecuteNonQuerys("Drop table " + username + "TMP" + i, CommandType.Text, ref error);
                if (kq)
                {
                    error = "OK";
                    //kq = dt.MyExecuteNonQuerys("CREATE TABLE " + username + "TMP7 ([ProgramID] [varchar] (20) NULL)ON [PRIMARY]  ", CommandType.Text, ref error);
                    //if (kq)
                    //{
                    //    error = "OK";
                    //}
                }
            }
        }
        if (PromotionByCustomer)
        {
            dt.MyExecuteNonQuery("Make_TMP1", CommandType.StoredProcedure, ref error, new SqlParameter("@usernames", username), new SqlParameter("@Pdate", PDate), new SqlParameter("@Custkey", Custkey), new SqlParameter("@login_Chanel", chanel));
        }
        else
        {
            dt.MyExecuteNonQuery("MakeTMP1", CommandType.StoredProcedure, ref error, new SqlParameter("@usernames", username), new SqlParameter("@Pdate", PDate), new SqlParameter("@login_Chanel", chanel));
        }
        TMP3 = dt.MyExecuteReaders(ref error, "select count(*) from " + username + "TMP1", CommandType.Text);
        if (TMP3 == null || TMP3 == "")
            TMP3 = "0";
        if (int.Parse(TMP3) == 0)
        {
            tmp = false;
            return tmp;
        }
        dt.MyExecuteNonQuery("create_TMP", CommandType.StoredProcedure, ref error, new SqlParameter("@usernames", username));
        // List cac mat hang ma ctringh km active trong khoang thoi gian nay
        dt.MyExecuteNonQuery("Insert_TMP2", CommandType.StoredProcedure, ref error, new SqlParameter("@usernames", username));
        //Theo cac mat hang trong list cac mat hang trong mua KM vao INPUT (fix truong hop mua theo bo hang)
        dt.MyExecuteNonQuery("Insert_INPUT", CommandType.StoredProcedure, ref error, new SqlParameter("@usernames", username));
        //dua cac mat hang tham gia KM vao TMP3
        dt.MyExecuteNonQuery("Insert_TMP3", CommandType.StoredProcedure, ref error, new SqlParameter("@usernames", username));
        //dt.MyExecuteNonQuery("update_TMP3", CommandType.StoredProcedure, ref error, new SqlParameter("@usernames", username));
        dt.MyExecuteNonQuery("Insert_TMP4", CommandType.StoredProcedure, ref error, new SqlParameter("@usernames", username));
        //Xoa cac Ctrinh KM (loai du bo) co so xuat KM=0
        dt.MyExecuteNonQuery("Del_KM0", CommandType.StoredProcedure, ref error, new SqlParameter("@usernames", username));
        //dt.MyExecuteNonQuery("Insert_TMP42", CommandType.StoredProcedure, ref error, new SqlParameter("@usernames", username));
        dt.MyExecuteNonQuery("Make_TMP5", CommandType.StoredProcedure, ref error, new SqlParameter("@usernames", username));
        //dt.MyExecuteNonQuery("Insert_TMP2", CommandType.StoredProcedure, ref error, new SqlParameter("@usernames", username));
        //MsgBox "ABC"
        dt.MyExecuteNonQuery("Insert_TMP4_TMP5", CommandType.StoredProcedure, ref error, new SqlParameter("@usernames", username));
        dt.MyExecuteNonQuerys("delete " + username + "TMP3 where Tvalue = 0", CommandType.Text, ref error);
        TMP3 = dt.MyExecuteReaders(ref error, "select count(ProgramID) from " + username + "TMP4", CommandType.Text);
        if (int.Parse(TMP3) == 0)
        {
            tmp = false;
        }
        else
        {
            tmp = true;
        }
        return tmp;
    }
}
